# _*_ coding:utf-8 _*_
from __future__ import print_function

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import JsonResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views.generic.base import View
from home.models import Banner, Peugeot
from users.models import UserProfile, EmailVerifyRecord, UserMessage
from utils.email_send import send_register_email
from .forms import LoginForm, RegisterForm, ForgetForm, ModifyPwdForm, PersonalForm, ActiveForm


#双登陆模块
class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            # 使用邮箱登陆和用户名登陆
            user = UserProfile.objects.get(Q(username=username)|Q(email=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


#激活view
class AciveUserView(View):
    def get(self, request,active_code):
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        active_form = ActiveForm(request.GET)
        if all_records:
            for recode in all_records:
                email = recode.email
                user = UserProfile.objects.get(email=email)
                user.is_active = True
                user.save()
                return render(request, "login.html", )
        else:
            return render(request, "register.html", {
                "msg": "您的激活链接无效", "active_form": active_form})



#使用类函数方法来验证 用户名 密码
#登陆view
class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                user_name = request.POST.get("username", "")
                pass_word = request.POST.get("password", "")
                user = authenticate(username=user_name, password=pass_word)
                if user is not None:
                    if user.is_active:
                        login(request, user)
                        return render(request, "user-base.html",
                                      )  # 登陆成功后跳转的页面
                    else:
                        return render(request, "login.html",{"msg": "用户名未激活! 请前往邮箱进行激活"})
                else:
                    return render(request, "login.html",{"msg": "用户名或密码错误!"})
            else:
                return render(request, "login.html",{"login_form": login_form})  # 登陆错误页面  login_form 错误信息 Type:list


#注册view
class RegisterView(View):

    def get(self, request):
        register_form = RegisterForm()
        return render(
            request, "register.html", { 'register_form': register_form})

    def post(self, request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            username = request.POST.get("email", "")
            if UserProfile.objects.filter(email=username):
                return render(request, 'register.html', {"register_form": register_form, "msg": "用户已经存在"})
            password = request.POST.get("password", "")
            user_profile = UserProfile()
            user_profile.username = username
            user_profile.email = username

            # 默认激活状态
            user_profile.is_active = False
            user_profile.password = make_password(password)
            user_profile.save()

            # 写入欢迎注册消息
            user_message = UserMessage()
            user_message.user = user_profile.id
            user_message.message = "欢迎注册!"
            user_message.save()

            send_register_email(username, "register")
            return render(request, "login.html")
        else:
            return render(request,"register.html",{"register_form":register_form})


#忘记密码
class ForgetPwdView(View):
    def get(self, request):
        forget_form = ForgetForm()
        return render(request, "forgetpwd.html", {"forget_form": forget_form})

    def post(self,request):
        forget_form = ForgetForm(request.POST)
        if forget_form.is_valid():
            email = request.POST.get("email", "")
            send_register_email(email, "forget")
            return render(request, "send_success.html")
        else:
            return render(request, "forgetpwd.html",{"forget_form":forget_form})


#重置密码
class ResetView(View):
    def get(self, request,active_code):
        all_records = EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:
            for recode in all_records:
                email = recode.email
                return render(request,"password_reset.html",{"email":email})
        else:
            return render(request,"active_fail.html")
        return render(request, "login.html")


class ModifyPwdView(View):
    def post(self, request):
        modify_form = ModifyPwdForm(request.POST)
        if modify_form.is_valid():
            pwd1 = request.POST.get("password1", "")
            pwd2 = request.POST.get("password2", "")
            email = request.POST.get("email","")
            if pwd1 != pwd2:
                return render(request,"password_reset.html", {"email": email, "msg": "密码不一致"})
            user = UserProfile.objects.get(email=email)
            user.password = make_password(pwd2)
            user.save()

            return render(request,"login.html")
        else:
            email = request.POST.get("email", "")
            return render(request, "password_reset.html", {"email": email,"modify_form":modify_form})


# 主页
class IndexView(View):
    def get(self, request):
        # 获取轮播图
        all_banner = Banner.objects.all().order_by('index')[:5]
        all_Peugeot = Peugeot.objects.all()
        return render(request, "index.html",
                      {"all_banner": all_banner, "all_Peugeot": all_Peugeot})

    def post(self, requset):
        return render(requset, "index.html")


# ajax请求数据
def ajax_data(request):
    user_name = request.GET.get("username")
    pass_word = request.GET.get("userpass")
    print(user_name, pass_word, "ok")
    # ajax获取数据 二次验证
    user = authenticate(username=user_name)
    if user is not None:
        if user.is_active:
            if request.user.is_authenticated():  # 验证登陆状态
                user_message = UserProfile.objects.get(username=user_name)
                users = {"nickname": user_message.nick_name, "gender": user_message.gender,
                         "mobile": user_message.mobile, "userid": user_message.userID,
                         "brokerid": user_message.brokerID, "pass": user_message.password_trader,
                         "address": user_message.address, "hello": "helloword"}
                return JsonResponse(users, safe=False)
            else:
                return render(request, "login.html", {"msg": "你还未登录，请先登录。"})
        else:
            return render(request, "login.html", {"msg": "用户未激活！"})
    else:
        return render(request, "login.html", {"msg": "用户名或密码不正确！"})


class UserInfoView(View):
    def get(self, request):
        return render(request, "user-base.html")

    def post(self, request):
        return render(request, "user-base.html")


# 退出登录
class LogoutView(View):
    def get(self, request):
        # django自带的logout
        logout(request)
        # 重定向到首页,
        return HttpResponseRedirect(reverse("index"))
